<template>
    <div style="margin: 250px auto;width: 600px;">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="Name">
                <el-input v-model="ruleForm.Name" />
            </el-form-item>
            <el-form-item label="密码" prop="PassWord">
                <el-input v-model="ruleForm.PassWord" show-password />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    登录
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { useCounterStore } from '@/stores/counter'
import router from '@/router';
import http from '@/http/axiosHelper';
const store = useCounterStore();



const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    Name: '',
    PassWord: ''
})

const rules = reactive<FormRules>({
    Name: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
    ],
    PassWord: [
        { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post("/api/Account/Login", ruleForm).then(res => {
                if (res.data.Code == 200) {
                    ElMessage.success(res.data.Message)
                    store.Account.Name = ruleForm.Name
                    store.Account.token = res.data.Data.token
                    store.Account.MenuTree = res.data.Data.MenuTree
                    store.Account.Department = res.data.Data.Department
                    store.Account.DepartmentHead = res.data.Data.DepartmentHead
                    store.Account.RoleName = res.data.Data.RoleName

                    router.push({ path: "/Main" })
                }
                else {
                    ElMessage.warning(res.data.Message)
                }
            })
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
